/**
 * $version:  0.1 
 * $Date: 2011-01-21 
 *
 * Copyright (C) 2010-2011 Jawa Open Source Grop. All rights reserved.
 *
 */

package com.cds.alert.filter;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion.User;

/**
 * 验证用户是否登录。
 * <p>
 * 	如果没有登录，则转向登录页面。
 * </p>
 * 
 * @author Y-N
 */
public class AuthCheckFilter implements Filter {

	private static final Logger Log = LoggerFactory.getLogger(AuthCheckFilter.class);

	// 系统登录页面
	private String loginPage;

	// 不进行过滤的页面
	private Pattern ignore;

	// 系统是否使用了框架，默认是否
	private Boolean useFrame = false;

	/**
	 * 初始化过滤器参数，包括系统的登录页面，不校验的页面等。
	 */
	public void init(FilterConfig config) throws ServletException {

		Log.debug(AuthCheckFilter.class.getName() + " 开始初始化!");

		loginPage = config.getInitParameter("form-login-page");
		if (null == loginPage) {
			loginPage = "/admin/login.jsp";
		}

		String useFrameStr = config.getInitParameter("useFrame");
		if (null != useFrameStr && Boolean.valueOf(useFrameStr)) {
			useFrame = true;
		}

		String ignoreStr = config.getInitParameter("ignore");
		if (ignoreStr != null && !"".equals(ignoreStr.trim())) {
			ignore = Pattern.compile(ignoreStr, Pattern.CASE_INSENSITIVE);
		}

		Log.debug("-- form-adminlogin-page :" + loginPage);
		Log.debug("-- useFrame :" + useFrame);
		Log.debug("-- ignore :" + ignore);
		Log.debug(AuthCheckFilter.class.getName() + " 结束初始化!");
		
	}

	/**
	 * 对访问的页页进行登录过滤。
	 */
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();

		// 得到当前要访问的页面
		String url = request.getRequestURL().toString();

		// 看当前要访问的页面是否在排除列表中。如果在跳过过滤器
		boolean doExclude = false;
		if (null == ignore || ignore.matcher(url).matches()) {
			doExclude = true;
		}

		if (!doExclude) {
//			User user = (User)session.getAttribute(JawaConstants.ADMIN_USER_KEY);
//			if (user == null) {
			if (false) {
				//当前访问的页面地址
				StringBuffer fromUrl = new StringBuffer("");
				if (request.getRequestURI() != null) {
					fromUrl.append(URLEncoder.encode(request.getRequestURI(), "UTF-8"));
					if (request.getQueryString() != null) {
						//可能有问题
						fromUrl.append("?");
						fromUrl.append(URLEncoder.encode(request.getQueryString(), "UTF-8"));
					}
				}
				
				String from = URLDecoder.decode(fromUrl.toString(), "UTF-8");
				
				loginPage = loginPage +"?from="+from;
				
				// 转向定义的失败页面
				if (Boolean.valueOf(useFrame)) {
					String pstrScript = " <script type=\"text/javascript\"> ";
					pstrScript += "window.top.location= '"+ request.getContextPath() + loginPage + "'; ";
					pstrScript += " </script> ";
					response.getOutputStream().print(pstrScript);
				} else {
					response.sendRedirect(request.getContextPath() + loginPage);
				}
				return;
			}
		}

		chain.doFilter(req, res);
	}

	public void destroy() {
		ignore = null;
	}

}
